package cn.keniykey.mc.landterritory.landflag.flag;

import java.util.Arrays;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;

import cn.keniykey.mc.landterritory.config.LanguageManager;
import cn.keniykey.mc.landterritory.event.LandTerritoryReloadConfigEvent;
import cn.keniykey.mc.landterritory.land.api.ILandManager;
import cn.keniykey.mc.landterritory.land.api.Land;
import cn.keniykey.mc.landterritory.landflag.api.ELandFlagParType;
import cn.keniykey.mc.landterritory.landflag.api.ELandFlagType;
import cn.keniykey.mc.landterritory.landflag.api.JavaLandFlag;
import cn.keniykey.mc.landterritory.landflag.api.LandFlagConfigurationFile;
import cn.keniykey.mc.landterritory.landflag.api.LandFlagListenerManager;
import cn.keniykey.mc.landterritory.toolkit.Util;

public final class BanPotionHurtFlag extends JavaLandFlag implements Listener{
	private String tip;
	
	@Override
	public ELandFlagType getELandFlagType() {
		return ELandFlagType.PLAYER;
	}
	@Override
	public ELandFlagParType getELandFlagParType() {
		return ELandFlagParType.MUCH;
	}
	@Override
	public boolean allowAllPlayerData() {
		return false;
	}
	
	@Override
	public void onEnable() {
		LandFlagListenerManager.registerListener(this, this);
	}
	@EventHandler
	public void onConfigLoad(final LandTerritoryReloadConfigEvent e) {
		final LandFlagConfigurationFile config = this.getLandFlagConfigurationFile();
		if(!config.has()) {
			config.set("name", "禁止使用伤害药水");
			config.set("lore", Arrays.asList("&7（禁止玩家在领地内使用伤害药水）","&7（瞬间伤害，中毒）","&5（标记参数为许可玩家）"));
			config.set("tip", "&c领地标记限制，不可以使用伤害药水");
		}
		this.setDisplayName(Util.conver(config.getString("name")));
		this.setIntroductionLore(Util.conver(config.getStringList("lore")));
		this.tip = LanguageManager.getChatPrefix() + Util.conver(config.getString("tip"));
	}
	
	@EventHandler(priority = EventPriority.LOW,ignoreCancelled = true)
	public void onPotionSplash(final PotionSplashEvent e) {
		for(final PotionEffect pe : e.getPotion().getEffects()) {
			if (!pe.getType().equals(PotionEffectType.POISON) && !pe.getType().equals(PotionEffectType.HARM)) continue;
			final ProjectileSource ps = e.getEntity().getShooter();
			if (ps == null || !(ps instanceof Player)) return;
			final Player player = (Player) ps;
			final Land land = ILandManager.getILandManager().getHighestPriorityLand(e.getEntity().getLocation());
			if(!JavaLandFlag.hasLandFlag(land, this)) {
				e.setCancelled(true);
				player.sendMessage(this.tip);
				break;
			}
		}
	}
}